package com.quartet.modules.stock.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quartet.api.ApiResult;
import com.quartet.api.MapServerException;
import com.quartet.api.PageResult;
import com.quartet.api.ResultErrorEnum;
import com.quartet.modules.stock.dto.TTerminalStockAddRequestDto;
import com.quartet.modules.stock.dto.TTerminalStockQueryRequestDto;
import com.quartet.modules.stock.dto.TTerminalStockResponseDto;
import com.quartet.modules.stock.entity.TFlowCardStock;
import com.quartet.modules.stock.entity.TTerminalStock;
import com.quartet.modules.stock.service.TFlowCardStockService;
import com.quartet.modules.stock.service.TTerminalStockService;
import com.quartet.utils.BeanTool;
import com.quartet.utils.constant.MapServerConstant;
import com.quartet.utils.enums.ActiveStatusEnum;
import com.quartet.utils.enums.InventoryStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 终端库存表(TTerminalStock)表控制层
 *
 * @author makejava
 * @since 2021-06-20 09:07:34
 */
@RestController
@RequestMapping("tTerminalStock")
@Slf4j
@Api(tags = "业务：终端库存管理")
public class TTerminalStockController {
    /**
     * 服务对象
     */
    @Resource
    private TTerminalStockService tTerminalStockService;
    /**
     * 服务对象
     */
    @Resource
    private TFlowCardStockService tFlowCardStockService;

    /**
     * 分页查询所有数据
     *
     * @param tTerminalStockQueryRequestDto 查询实体
     * @return 所有数据
     */
    @PostMapping("/queryTerminalStockPage")
    @ApiOperation("/分页查询所有终端库存数据")
    public ApiResult<PageResult<TTerminalStockResponseDto>> queryTerminalStockPage(@RequestBody TTerminalStockQueryRequestDto tTerminalStockQueryRequestDto) {
        log.info("---------queryTerminalStockPage begin, tTerminalStockQueryRequestDto is {}----------", tTerminalStockQueryRequestDto);
        IPage<TTerminalStock> page = new Page<>(tTerminalStockQueryRequestDto.getCurrent(), tTerminalStockQueryRequestDto.getLimit());
        QueryWrapper<TTerminalStock> queryWrapper = new QueryWrapper<>();

        if (!ObjectUtils.isEmpty(tTerminalStockQueryRequestDto.getInventoryStatus())) {
            queryWrapper.lambda().eq(TTerminalStock::getInventoryStatus, tTerminalStockQueryRequestDto.getInventoryStatus());
        }
        if (!ObjectUtils.isEmpty(tTerminalStockQueryRequestDto.getTerminalCode())) {
            queryWrapper.lambda().like(TTerminalStock::getTerminalCode, tTerminalStockQueryRequestDto.getTerminalCode());
        }

        if (StringUtils.isNotBlank(tTerminalStockQueryRequestDto.getField())) {
            queryWrapper.orderBy(true, tTerminalStockQueryRequestDto.isAsc(), tTerminalStockQueryRequestDto.getField());
        } else {
            queryWrapper.orderBy(true, tTerminalStockQueryRequestDto.isAsc(), MapServerConstant.CREATE_TIME);
        }
        IPage<TTerminalStock> dbResult = tTerminalStockService.page(page, queryWrapper);
        PageResult<TTerminalStockResponseDto> pageResult = new PageResult();
        List<TTerminalStockResponseDto> tTerminalStockResponseDtoList = dbResult.getRecords().stream().map(tTerminalStock -> {
            TTerminalStockResponseDto tTerminalStockResponseDto = BeanUtil.copyProperties(tTerminalStock, TTerminalStockResponseDto.class);
            return tTerminalStockResponseDto;
        }).collect(Collectors.toList());
        pageResult.setTotal(dbResult.getTotal());
        pageResult.setData(tTerminalStockResponseDtoList);
        log.info("---------queryTerminalStockPage end, data is {}----------", pageResult);
        return ApiResult.ok(pageResult);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/getTerminalStockById")
    @ApiOperation("/通过主键查询单条终端库存数据")
    public ApiResult<TTerminalStockResponseDto> getTerminalStockById(@RequestParam("id") Integer id) {
        TTerminalStock tTerminalStock = tTerminalStockService.getById(id);
        TTerminalStockResponseDto tTerminalStockResponseDto = BeanUtil.copyProperties(tTerminalStock, TTerminalStockResponseDto.class);
        return ApiResult.ok(tTerminalStockResponseDto);
    }

    /**
     * 新增数据
     *
     * @param tTerminalStockAddRequestDto 实体对象
     * @return 新增结果
     */
    @PostMapping("/addTerminalStock")
    @ApiOperation("/新增单条终端库存数据")
    public ApiResult addTerminalStock(@RequestBody TTerminalStockAddRequestDto tTerminalStockAddRequestDto) {
        QueryWrapper<TTerminalStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TTerminalStock::getTerminalCode, tTerminalStockAddRequestDto.getTerminalCode());
        List<TTerminalStock> list = tTerminalStockService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            throw new MapServerException(ResultErrorEnum.BMKPZ005);
        }
        TTerminalStock tTerminalStock = BeanUtil.copyProperties(tTerminalStockAddRequestDto, TTerminalStock.class);
        tTerminalStock.setStorageTime(LocalDateTime.now());
        tTerminalStock.setInventoryStatus(InventoryStatusEnum.UNALLOCATED.getValue());
        tTerminalStockService.save(tTerminalStock);
        return ApiResult.ok();
    }

    /**
     * 修改数据
     *
     * @param tTerminalStockAddRequestDto 实体对象
     * @return 修改结果
     */
    @PutMapping("/updateTerminalStock")
    @ApiOperation("/修改单条终端库存数据")
    public ApiResult updateTerminalStock(@RequestBody TTerminalStockAddRequestDto tTerminalStockAddRequestDto) {
        QueryWrapper<TTerminalStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TTerminalStock::getTerminalCode, tTerminalStockAddRequestDto.getTerminalCode())
                .ne(TTerminalStock::getId, tTerminalStockAddRequestDto.getId());
        List<TTerminalStock> list = tTerminalStockService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            throw new MapServerException(ResultErrorEnum.BMKPZ005);
        }
        TTerminalStock tTerminalStock = BeanUtil.copyProperties(tTerminalStockAddRequestDto, TTerminalStock.class);
        tTerminalStockService.updateById(tTerminalStock);
        return ApiResult.ok();
    }

    /**
     * 删除数据
     *
     * @param idList 主键集合
     * @return 删除结果
     */
    @DeleteMapping("/deleteTerminalStock")
    @ApiOperation("/删除单条终端库存数据")
    public ApiResult deleteTerminalStock(@RequestBody List<Integer> idList) {
        tTerminalStockService.removeByIds(idList);
        return ApiResult.ok();
    }

    /**
     * 批量导入
     *
     * @param multipartFile 上传文件流
     * @return 删除结果
     */
    @PostMapping("/batchImportTerminalStock")
    @ApiOperation("/批量导入终端库存数据")
    public ApiResult batchImportTerminalStock(@RequestParam("multipartFile") MultipartFile multipartFile) throws IOException {
        tTerminalStockService.batchImportTerminalStock(multipartFile);
        return ApiResult.ok();
    }

    /**
     * 批量导出
     *
     * @param idList 主键集合
     * @return 删除结果
     */
    @PostMapping("/batchExportTerminalStock")
    @ApiOperation("/批量导出终端库存数据")
    public ApiResult batchExportTerminalStock(HttpServletRequest request, HttpServletResponse response, @RequestBody(required = false) List<Integer> idList) throws IOException {
        tTerminalStockService.batchExportTerminalStock(response, idList);
        return ApiResult.ok();
    }

    /**
     * 终端库存导入模板下载
     *
     * @param request  主键集合
     * @param response 主键集合
     * @return 下载结果
     */
    @PostMapping("/downloadExportTerminalStockTemplate")
    @ApiOperation("/批量导出终端库存数据")
    public ApiResult downloadExportTerminalStockTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取要下载的文件的绝对路径
//        String realPath = "E:\\file\\template\\终端库存导入模板.xls";
        String realPath = "/home/workspace/template/terminal.xls";
        //2.获取要下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf(File.separator) + 1);
        String agent = request.getHeader("User-Agent").toUpperCase(); //获得浏览器信息并转换为大写
        byte[] bytes = agent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");
        // 各浏览器基本都支持ISO编码
        fileName = new String(bytes, "utf-8");
        // 文件名外的双引号处理firefox的空格截断问题
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
        //获取文件输入流
        InputStream in = new FileInputStream(realPath);
        OutputStream out = response.getOutputStream();
        IOUtils.copy(in, out);
        out.close();
        in.close();
        return ApiResult.ok();
    }

    /**
     * 修改库存状态
     *
     * @param terminalCode   终端编码
     * @param flowCardNumber 流量卡编码
     * @return 删除结果
     */
    @PostMapping("/updateTerminalStockStatus")
    @ApiOperation("/修改终端库存状态")
    @ApiImplicitParams({@ApiImplicitParam(name = "terminalCode", value = "终端编码"),
            @ApiImplicitParam(name = "flowCardNumber", value = "流量卡号"),
            @ApiImplicitParam(name = "InventoryStatus", value = "分配状态 0：已出库 1：未出库 2:待出库")})
    public ApiResult updateTerminalStockStatus(@RequestParam("terminalCode") String terminalCode,
                                               @RequestParam("flowCardNumber") String flowCardNumber,
                                               @RequestParam("InventoryStatus") String InventoryStatus) {
        log.info("updateTerminalStockStatus bean, param is :{},{},{}",terminalCode,flowCardNumber,InventoryStatus);
        //修改终端库存状态
        UpdateWrapper<TTerminalStock> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(TTerminalStock::getTerminalCode, terminalCode)
                .set(TTerminalStock::getInventoryStatus, InventoryStatus)
                .set(TTerminalStock::getOrderCode,"")
                .set(TTerminalStock::getDeliveryTime, null);
        tTerminalStockService.update(updateWrapper);
        //修改流量卡库存状态
        UpdateWrapper<TFlowCardStock> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.lambda().eq(TFlowCardStock::getFlowCardNumber, flowCardNumber)
                .set(TFlowCardStock::getInventoryStatus, ActiveStatusEnum.UNALLOCATED.getValue())
                .set(TFlowCardStock::getDeliveryTime,null);
        tFlowCardStockService.update(updateWrapper1);
        log.info("updateTerminalStockStatus success");
        return ApiResult.ok();
    }

    /**
     * 终端下拉列表
     *
     * @return
     */
    @GetMapping("/selectTerminalList")
    @ApiOperation("/终端下拉列表")
    public ApiResult<List<TTerminalStockResponseDto>> selectTerminalList(@RequestParam(value = "orderCode",required = false) String orderCode) {
        QueryWrapper<TTerminalStock> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(TTerminalStock::getInventoryStatus,InventoryStatusEnum.TOBEALLOCATED.getValue())
                .eq(TTerminalStock::getOrderCode,"");
        List<TTerminalStock> tTerminalInfoList = tTerminalStockService.list(queryWrapper);
        List<TTerminalStockResponseDto> tTerminalStockResponseDtoList = BeanTool.copyObjListProperties(tTerminalInfoList, TTerminalStockResponseDto.class);
        if (StringUtils.isNotBlank(orderCode)){
            List<TTerminalStock> tTerminalStockList = tTerminalStockService.list(new QueryWrapper<TTerminalStock>().lambda().eq(TTerminalStock::getOrderCode, orderCode));
            if (!CollectionUtils.isEmpty(tTerminalStockList)){
                tTerminalStockResponseDtoList.addAll(BeanTool.copyObjListProperties(tTerminalStockList,TTerminalStockResponseDto.class));
            }
        }
        return ApiResult.ok(tTerminalStockResponseDtoList);
    }
}
